/**
 * 
 */
package com.zznode.client.wlanpolling.model;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * @author Pink
 *
 */
public class WebSiteManager {
	private static WebSiteManager instance;
	private static Context context;
	
	public static void init(Context contex) {
		WebSiteManager.context = contex;
	}
	
	public static synchronized WebSiteManager getWebSiteManager() {
		if(instance == null) {
			instance = new WebSiteManager();
		}
		return instance;
	}
	
	public List<WebSite> getAllWebSite() {
		List<WebSite> result = new ArrayList<WebSite>();
		
		DatabaseHelper dbHelper = new DatabaseHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		Cursor cursor = db.query(DatabaseHelper.TABLE_WEBSITE,
				new String[]{"name", "url"}, null, null,
				null, null, null);
		if(cursor.moveToFirst()) {
			do{
				WebSite webSite = new WebSite(cursor.getString(0), cursor.getString(1));
				result.add(webSite);
			} while(cursor.moveToNext());
		}
		
		cursor.close();
		db.close();
		
		return result;
	}
	
	public void addWebSite(String name, String url) {
		DatabaseHelper dbHelper = new DatabaseHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		
		Cursor cursor = db.query(DatabaseHelper.TABLE_WEBSITE,
				new String[]{"name", "url"}, "name=?", new String[]{name},
				null, null, null);
		
		ContentValues values = new ContentValues();
		values.put("name", name);
		values.put("url", url);
		
		if(cursor.moveToFirst()) {
			//update
			db.update(DatabaseHelper.TABLE_WEBSITE, values, "name=?", new String[]{name});
		} else {
			//insert
			db.insert(DatabaseHelper.TABLE_WEBSITE, "name", values);
		}
		
		cursor.close();
		db.close();
	}
	
	public void deleteWebSite(String name) {
		DatabaseHelper dbHelper = new DatabaseHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.delete(DatabaseHelper.TABLE_WEBSITE, "name=?", new String[]{name});
		db.close();
	}
}
